{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3小时Python入门"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 一，编程环境"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "推荐 Jupyter Notebook.\n",
    "\n",
    "1, 可以下载安装Anaconda 使用 jupyter notebook\n",
    "\n",
    "2，也可以注册聚宽账号(https://www.joinquant.net/)，\n",
    "   在\"我的策略\"-->\"投资研究\"中可以直接使用jupyter notebook\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在jupyter notebook 中使用快键键\n",
    "Ctrl+Enter\n",
    "运行单元格cell中的代码。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "《3小时Python入门》 网易云课堂视频地址：   \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://study.163.com/course/introduction/1005839001.htm\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "关注微信公众号：Python与算法之美\n",
    "\n",
    "获得更多Python编程和机器学习实用教程分享。\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  二，算术运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "31.0"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1+(100-20)/4+5*2   #四则运算\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1024"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "2**10  #乘方运算\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "7%5  #求模运算\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "7//5  #地板除法\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.0"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.sin(pi/2)  #三角函数\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "abs(-1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.0"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.log(e) #对数函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "120"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.factorial(5) #阶乘"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(4+1j)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(1 + 2j) + (3 - 1j)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.6+0.8j)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "complex(2,1)/(2 - 1j)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001267650600228229401496703205376"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.factorial(1000) + 2**100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 三，输入输出"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "输入:input\n",
    "\n",
    "输出:print"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "please input your weight:54\n"
     ]
    }
   ],
   "source": [
    "#input 输入的都是字符串\n",
    "weight = input('please input your weight:')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "please input your weight:43\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "43.0"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#利用float函数将字符串转换成浮点数\n",
    "weight = float(input('please input your weight:'))\n",
    "weight"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "please input your age:2018-1999\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "19"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 利用eval函数将输入的字符串作为表达式进行计算\n",
    "age = eval(input('please input your age:'))\n",
    "age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "your weight is: 43.0\n"
     ]
    }
   ],
   "source": [
    "# 输出用print\n",
    "print('your weight is:',weight)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 四，导入模块"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "import ...\n",
    "\n",
    "或 from ... import ...\n",
    "\n",
    "或 import ... as ..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.datetime(2018, 9, 22, 22, 33, 50, 56469)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 以普通方式导入\n",
    "\n",
    "import datetime\n",
    "datetime.datetime.today()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.datetime(2018, 9, 22, 22, 33, 52, 361536)"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 导入模块中某个对象\n",
    "\n",
    "from datetime import datetime\n",
    "datetime.today()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.date(2018, 1, 1)"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 导入模块中全部对象\n",
    "\n",
    "from datetime import *\n",
    "datetime.today()\n",
    "date(2018,1,1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime.datetime(2018, 9, 22, 22, 33, 58, 436262)"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 以简写方式导入模块\n",
    "\n",
    "import datetime as dt\n",
    "dt.datetime.today()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 五，语法规则"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "1，标识符\n",
    "\n",
    "标识符由字母、数字、下划线组成，区分大小写，不能以数字开头。\n",
    "以下划线开头的标识符有特殊含义。以单下划线开头的（_foo）的代表不能直接访问的类属性，\n",
    "以双下划线开头的（__foo）代表类的私有成员；\n",
    "以双下划线开头和结尾的(__foo__)代表Python里特殊方法专用的标识，\n",
    "如__init__() 代表类的构造函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1.9.3'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy \n",
    "numpy.__version__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2，缩进\n",
    "\n",
    "Python的代码块不使用大括号来控制类、函数、以及其他逻辑判断，而是使用缩进来写实现代码分组。通常用四个空格来进行缩进。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "a,b = 1,2\n",
    "if a>b:\n",
    "    x = a\n",
    "else:\n",
    "    x = b\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3，注释\n",
    "\n",
    "python中单行注释采用 # 开头。\n",
    "多行注释使用三个单引号(''')或三个双引号(\"\"\")。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "author:Python_Ai_Road\n",
    "date:2018-08-05\n",
    "\"\"\"\n",
    "def my_abs(x): #绝对值函数\n",
    "    if x >= 0:\n",
    "        return(x)\n",
    "    else:\n",
    "        return(-x)\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4，一条语句分多行显示\n",
    "\n",
    "Python语句中一般以新行作为为语句的结束符。\n",
    "但是我们可以使用斜杠（ \\）将一行的语句分为多行显示。\n",
    "如果有{},[],()跨行则可以不使用\\"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "62"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1+2+3+4+5+6+7+\\\n",
    "7+8+9+10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [1,2,3,4,\n",
    "    5,6,7,8]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "5, 同一行显示多条语句\n",
    "\n",
    "Python可以在同一行中使用多条语句，语句之间使用分号分割。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "a=1;b=a+5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 六，Python数据结构概述"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "python内建的数据结构有列表，元组，字符串，字典，集合等。\n",
    "\n",
    "此外常用的还有numpy中的array，以及pandas中的dataframe和series。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1，有序数据结构： \n",
    "\n",
    "list（列表），是有序集合，没有固定大小，可以通过对偏移量以及其他方法修改列表大小。列表的基本形式如：[1,2,3,4] \n",
    "\n",
    "tuple（元组），是有序集合，是不可变的，可以进行组合和复制运算后会生成一个新的元组。元组的基本形式比如：(1,3,6,10) \n",
    "\n",
    "str（字符串），也是有序集合，字符串的基本形式比如：’hello'。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[3, 2, 3, 4]"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l = [1,2,3,4]\n",
    "print(l[0])\n",
    "l[0] = 3\n",
    "l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2，无序数据结构：\n",
    "\n",
    "set（集合），是一个无序不重复元素的集。\n",
    "基本功能包括关系运算和消除重复元素。集合的基本形式如：\n",
    "{'apple','orange','banana'}\n",
    "\n",
    "dict（字典）是无序的键：值对 (key:value 对)的集合。\n",
    "键必须是互不相同的(在同一个字典之内)。\n",
    "字典的基本形式如：{'ICBC': 95588, 'BOC': 95566}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "95566"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = {'ICBC': 95588, 'BOC': 95566}\n",
    "d['BOC']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 七，列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[0, 1, 2], [1, 2, 3]]"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 1,建立列表\n",
    "\n",
    "fruits = ['apple','orange','banana']\n",
    "a = list(range(1,11,2))\n",
    "b = [2**i  for i in range(5)]\n",
    "c = [[i+j for i in range(3)] for j in range(2)]\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 3, 5, 7, 9]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[1, 3, 5]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 2,访问列表\n",
    "# 列表支持下标访问和切片访问\n",
    "\n",
    "print(a)\n",
    "a[0]\n",
    "a[-1]\n",
    "a[-2]\n",
    "\n",
    "a[0:3]\n",
    "a[0:3:2]\n",
    "a[0:]\n",
    "a[:-2]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 3,修改列表\n",
    "\n",
    "a[0] = 0\n",
    "a.remove(5)  #删除元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 7, 9]"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "del(a[0])\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 7, 9, 1, 2, 3]"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a + [1,2,3]  # +号对序列有拼接作用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 7, 9, 3, 7, 9, 3, 7, 9]"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a * 3  # *号有复制拷贝多份效果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[9, 7, 3]"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 4,列表常用函数\n",
    "\n",
    "len(a)\n",
    "\n",
    "max(a)\n",
    "\n",
    "min(a)\n",
    "\n",
    "sorted(a,reverse = True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 5,列表常用方法\n",
    "\n",
    "a.extend([8,10])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "a.append(11)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 3, 7, 9, 8, 10, 11]"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.insert(0,1)\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 八，字典\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字典在插入元素和查找元素方面很多时候比列表更加高效。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 1,创建字典\n",
    "\n",
    "d = {1:3,2:4,3:6}\n",
    "a = dict([('a',1),['b',2]])\n",
    "b = dict(x = 1,y = 2)\n",
    "\n",
    "D = {i:i**2 for i in range(5)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "D"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 2,字典常用操作\n",
    "\n",
    "a['a'] = 3\n",
    "a['c'] = 5\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['b', 'a', 'c'])"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_values([2, 3, 5])"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.values()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_items([('b', 2), ('a', 3), ('c', 5)])"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.items()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 3, 'b': 2, 'c': 5}"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 3, 'b': 3, 'c': 5, 'd': 10}"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.update({'b':3,'d':10})\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.get('e',0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.setdefault('a',4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 3, 'b': 3, 'c': 5, 'd': 10, 'e': 4}"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.setdefault('e',4)\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 3, 'b': 3, 'c': 5, 'd': 10, 'e': 4}"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.copy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 九，字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm Jimmy.\n",
      "I just use Python to say:\"hello world\"!\n"
     ]
    }
   ],
   "source": [
    "### 1,创建字符串\n",
    "s1 = 'I\\'m Jimmy.\\nI just use Python to say:\"hello world\"!'\n",
    "print(s1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm Jimmy.\n",
      "I just use Python to say:\"hello world\"!\n"
     ]
    }
   ],
   "source": [
    "s2 = \"I'm Jimmy.\\nI just use Python to say:\\\"hello world\\\"!\"\n",
    "print(s2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm Jimmy.\n",
      "I just use Python to say:\"hello world\"!\n"
     ]
    }
   ],
   "source": [
    "s3 = '''I'm Jimmy.\n",
    "I just use Python to say:\"hello world\"!'''\n",
    "print(s3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'I\\'m Jimmy.\\nI just use Python to say:\"hello world\"!'"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'12345'"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(12345)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm Jimmy.\n",
      "I love Python.\n",
      "I just use Python to say:\"hello world\"!\n"
     ]
    }
   ],
   "source": [
    "### 2,字符串拼接(+,join)\n",
    "\n",
    "s1 = \"I'm Jimmy.\"\n",
    "s2 = \"I love Python.\"\n",
    "s3 = 'I just use Python to say:\"hello world\"!'\n",
    "\n",
    "s = s1 + '\\n' + s2 + '\\n' + s3\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm Jimmy.\n",
      "I love Python.\n",
      "I just use Python to say:\"hello world\"!\n"
     ]
    }
   ],
   "source": [
    "print('\\n'.join([s1,s2,s3]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'abcabcabcabcabc'"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"abc\" * 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'abcdefxyz'"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 3,清洗字符串(replace,strip)\n",
    "\n",
    "\"$$$abcdef$$xyz\".replace('$','')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'abc123'"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\\nabc123\\t\".strip()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Jimmy', '18', 'male']"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Jimmy\\t18\\tmale\".split('\\t')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm 19 years old. My weight is 60.50 kg. I like travelling\n"
     ]
    }
   ],
   "source": [
    "### 4,格式化字符串(%或format)\n",
    "age = 19\n",
    "weight = 60.5\n",
    "hobby = 'travelling'\n",
    "# %d表示整数， %f表示浮点数， %s表示字符串\n",
    "\n",
    "fs = \"I'm %d years old. My weight is %.2f kg. I like %s\" %(age,weight,hobby)\n",
    "print(fs)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"I'm 19 years old. My weight is 60.50 kg. I like travelling\""
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fs = \"I'm {} years old. My weight is {:.2f} kg. I like {}\" .format(age,weight,hobby)\n",
    "fs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十，元组 tuple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1,创建元组\n",
    "t = (1,2,3)\n",
    "t0 = ()\n",
    "t1 = (1,)\n",
    "x = 1,2\n",
    "\n",
    "y = tuple([1,2,3])\n",
    "z = tuple('abc')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2,使用元组\n",
    "\n",
    "t.count(1)\n",
    "t.index(3)\n",
    "\n",
    "#序列解包\n",
    "a,b = 1,2\n",
    "t1,t2,t3 = [1,2,3]\n",
    "\n",
    "#元组可以作为字典key\n",
    "\n",
    "d = {(1,2):4}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{(1, 2): 4}"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3,浅拷贝与深拷贝\n",
    "\n",
    "t2 = t"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [],
   "source": [
    "l = [1,2,3]\n",
    "l3 = l.copy() # 深拷贝开辟新的内存空间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [],
   "source": [
    "l3[0] = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 2, 3]"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3]"
      ]
     },
     "execution_count": 72,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [],
   "source": [
    "l2 = l   #浅拷贝只是原来对象的一个别名。\n",
    "l2[0] = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 2, 3]"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 2, 3]"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十一，集合 Set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1，创建集合\n",
    "\n",
    "s = {1,2,3}\n",
    "s0 = set()\n",
    "\n",
    "s3 = {x**2 for x in range(3)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{0, 1, 4}"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2，使用集合\n",
    "\n",
    "#去除重复对象，求交集，并集，补集等操作\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = [1,2,3,3,5,6,7,5,8,7]\n",
    "\n",
    "len(set(a))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [],
   "source": [
    "s1 = {1,2,3,6,7}\n",
    "s2 = {2,5,8,10}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{2}"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s1 & s2 #交集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3, 5, 6, 7, 8, 10}"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s1 | s2 #并集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 3, 6, 7}"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s1.difference(s2)  #广义补集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十二，条件语句if "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 1, if语句\n",
    "a,b = 3,2\n",
    "\n",
    "if a>b:\n",
    "    x = a\n",
    "else:\n",
    "    x = b\n",
    "    \n",
    "#if...elif..elif...else...\n",
    "\n",
    "y = a if a>b else b\n",
    "y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 2, 逻辑运算符\n",
    "\n",
    "2>3\n",
    "1+2<100\n",
    "3 == 4-1\n",
    "2 != 3\n",
    "\n",
    "not 2==3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{3, 4}"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 3, and和or\n",
    "\n",
    "2>3 and 4<5\n",
    "2>3 or 4<5\n",
    "\n",
    "x = [] or [1,2,3] or {}  #短路计算，注意空字典和空列表为false\n",
    "y = 50 and {1} and {3,4} \n",
    "y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(False, True, True)"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bool(''),bool([1]),bool(-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十三，循环语句 for，while"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "5\n",
      "4\n",
      "3\n",
      "b : 2\n",
      "a : 1\n",
      "c : 3\n"
     ]
    }
   ],
   "source": [
    "# 1,for循环\n",
    "\n",
    "l = [1,2,5,4,3]\n",
    "for i in l:\n",
    "    print(i)\n",
    "\n",
    "d = {'a':1,'b':2,'c':3}\n",
    "for k,v in d.items():\n",
    "    print(k,':',v)   \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "source": [
    "#求 l中最大的元素\n",
    "l = [1,2,5,4,3]\n",
    "max(l)\n",
    "max_l = l[0]\n",
    "for i in l:\n",
    "    max_l = i if i>max_l else max_l\n",
    "print(max_l)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('b', 2), ('a', 1), ('c', 3)]"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(d.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5050 101\n"
     ]
    }
   ],
   "source": [
    "# 2,while循环\n",
    "\n",
    "#求1+2+3+...+100\n",
    "s,i = 0,1\n",
    "while i<=100:\n",
    "    s = s + i\n",
    "    i = i + 1\n",
    "print(s,i)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n",
      "\n",
      "helloworld"
     ]
    }
   ],
   "source": [
    "# 3,循环控制continue,break\n",
    "\n",
    "s = 'hello world'\n",
    "\n",
    "# break跳出本层循环\n",
    "for i in s:\n",
    "    if i ==' ':\n",
    "        break\n",
    "    print(i,end = '')\n",
    "\n",
    "print('\\n')\n",
    "\n",
    "# continue跳出本次循环\n",
    "for i in s:\n",
    "    if i ==' ':\n",
    "        continue\n",
    "    print(i,end = '')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十四，函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 94,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#1,函数参数：普通参数,默认参数,可变参数,关键字参数\n",
    "#普通参数(位置参数)\n",
    "\n",
    "def my_abs(x):\n",
    "    return(x if x>=0 else -x)\n",
    "\n",
    "my_abs(-5)\n",
    "my_abs(x = 5)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "125"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#默认参数 n(参数缺失时赋默认值)\n",
    "\n",
    "def my_power(x,n = 2):\n",
    "    return(x**n)\n",
    "\n",
    "my_power(5)\n",
    "my_power(x = 5,n = 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 96,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#可变参数 *args(可以传入不定长度参数序列，元组或列表)\n",
    "\n",
    "def my_sum(*args):\n",
    "    s = 0\n",
    "    for i in args:\n",
    "        s = s + i\n",
    "    return(s)\n",
    "my_sum(1,2,3)\n",
    "my_sum()\n",
    "my_sum(*(1,2,3))\n",
    "my_sum(*[1,2,3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'age': 18, 'grade': '13', 'hometown': 'London', 'name': 'Jim'}"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#关键字参数 **kv(可以传入字典)\n",
    "\n",
    "def student(name,age,**kv):\n",
    "    d = {'name':name,'age':age}\n",
    "    d.update(kv)\n",
    "    return(d)\n",
    "\n",
    "student('LiLei',19,grade = '13',gender = 'male')\n",
    "Jim = {'name':'Jim','age':18,'grade':'13','hometown':'London'}\n",
    "student(**Jim)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6765"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#2,递归函数\n",
    "#递归函数调用自身\n",
    "\n",
    "def fib(n):\n",
    "    if n in [1,2]:\n",
    "        return(1)\n",
    "    else:\n",
    "        return(fib(n-1) + fib(n-2))\n",
    "fib(20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [],
   "source": [
    "#3,装饰器\n",
    "\n",
    "#装饰器在不更改函数代码前提下赋予函数额外的功能\n",
    "#通常把函数非核心逻辑如插入日志、权限校验、性能测试放在装饰器中\n",
    "\n",
    "import time\n",
    "def runtime(func):\n",
    "    def wrapper(*args,**kv):\n",
    "        tic = time.time()\n",
    "        ans = func(*args,**kv)\n",
    "        toc = time.time()\n",
    "        print('{} is called. {}s used'.\n",
    "              format(func.__name__,toc-tic))\n",
    "        return(ans)\n",
    "    return(wrapper)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [],
   "source": [
    "@runtime\n",
    "def my_sum(*args):\n",
    "    s = 0\n",
    "    for i in args:\n",
    "        s = s + i\n",
    "    return(s)\n",
    "# @runtime是一个语法糖\n",
    "# 相当于 my_sum = runtime(my_sum)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "my_sum is called. 1.8358230590820312e-05s used\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "4950"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_sum(*range(100))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "my_sum is called. 3.5762786865234375e-06s used\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 103,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_sum(1,2,3)  #相当于 runtime(my_sum)(1,2,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fib is called. 1.1920928955078125e-06s used\n",
      "fib is called. 1.1920928955078125e-06s used\n",
      "fib is called. 5.269050598144531e-05s used\n",
      "fib is called. 1.1920928955078125e-06s used\n",
      "fib is called. 7.557868957519531e-05s used\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 104,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@runtime\n",
    "def fib(n):\n",
    "    if n in [1,2]:\n",
    "        return(1)\n",
    "    else:\n",
    "        return(fib(n-1) + fib(n-2))\n",
    "fib(4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十五，lambda匿名函数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "lambda只是一个表达式，适合定义较为简单的函数。\n",
    "\n",
    "lambda函数的定义语法是：\n",
    "\n",
    "fun = lambda 参数序列：返回值表达式\n",
    "\n",
    "一般来说通过使用lambda匿名函数可以节约程序开支并加快运行速度。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 105,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_abs = lambda x: x if x>=0 else -x\n",
    "my_abs(-5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "25"
      ]
     },
     "execution_count": 106,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_power = lambda x,n=2:x**n\n",
    "my_power(-5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-125"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(lambda x,n=2:x**n)(-5,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 108,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_sum = lambda *args:sum(args)\n",
    "my_sum(1,2,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'age': 18, 'grade': '13', 'name': 'LiLei'}"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "student = lambda name,age,**kv:dict(name = name,age = age,**kv)\n",
    "student('LiLei',18,grade = '13')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'age': 18, 'grade': '13', 'name': 'LiLei'}"
      ]
     },
     "execution_count": 110,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = {'name':'LiLei','age':18}\n",
    "d.update({'grade':'13'})\n",
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "NoneType"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(d.update({'grade':'13'}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "55"
      ]
     },
     "execution_count": 112,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fib = lambda n: 1 if n in [1,2] else fib(n-1)+fib(n-2)\n",
    "fib(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  十六，高阶函数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以函数为参数的函数叫做高阶函数。常用的内置高阶函数有：map,reduce,filter。\n",
    "\n",
    "高阶函数和匿名函数搭配使用,堪称绝配。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 4, 9, 16]"
      ]
     },
     "execution_count": 113,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1,map将一个函数作用到一个序列或者多个序列配对\n",
    "#map英文单词原意:映射\n",
    "\n",
    "list(map(lambda x:x**2,[1,2,3,4]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a1', 'b2', 'c3']"
      ]
     },
     "execution_count": 114,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(map(lambda x,y:x+y,'abc','123'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10"
      ]
     },
     "execution_count": 115,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 2,reduce 将一个带有两个参数的函数依次迭代作用到一个序列\n",
    "#reduce英文单词原意：减少\n",
    "#reduce(f,[a,b,c,d]) = f(f(f(a,b),c),d)\n",
    "\n",
    "from functools import reduce\n",
    "reduce(lambda x,y:x+y,[1,2,3,4])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2]"
      ]
     },
     "execution_count": 116,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 3,filter 根据规则过滤序列中的元素\n",
    "#filter英文单词愿意：过滤\n",
    "\n",
    "list(filter(lambda x:x>0,[-1,-2,1,2]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十七，Python推导式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python中的推导式是我最喜爱的一类语法规则，没有之一。\n",
    "\n",
    "Python推导式可以生成列表,字典和集合。\n",
    "\n",
    "Python推导式虽然简单，但表达能力很强，可以实现map,filter等功能,并且可以多重遍历。\n",
    "\n",
    "淋漓尽致地体现了Python语言的simple,readable,powerful的特点。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('Jim', 'Mary'), ('Jim', 'Lily'), ('John', 'Mary'), ('John', 'Lily')]"
      ]
     },
     "execution_count": 117,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 1，列表推导式\n",
    "\n",
    "#生成平方数序列\n",
    "[x**2 for x in range(4)]\n",
    "\n",
    "#求序列的绝对值\n",
    "l = [-1,-2,3,4,-2]\n",
    "[x if x>0 else -x for x in l]\n",
    "\n",
    "list(map(lambda x:x if x>0 else -x,l))\n",
    "\n",
    "#过滤序列中某些元素\n",
    "[x for x in l if x>0]\n",
    "list(filter(lambda x:x>0, l))\n",
    "\n",
    "#多重遍历\n",
    "girls = ['Mary','Lily']\n",
    "boys = ['Jim','John']\n",
    "couples = [(b,g) for b in boys for g in girls]\n",
    "couples\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 118,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1: 'Spring', 2: 'Summer', 3: 'Autumn', 4: 'Winter'}"
      ]
     },
     "execution_count": 118,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 2,字典推导式\n",
    "\n",
    "seasons = ['Spring','Summer','Autumn','Winter']\n",
    "d = {k:v for k,v in enumerate(seasons,start = 1)} \n",
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(1, 'Spring'), (2, 'Summer'), (3, 'Autumn'), (4, 'Winter')]"
      ]
     },
     "execution_count": 119,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(enumerate(seasons,start = 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 120,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 1, 'b': 2, 'c': 3}"
      ]
     },
     "execution_count": 120,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "keys = ['a','b','c']\n",
    "values = [1,2,3]\n",
    "D = {k:v for k,v in zip(keys,values)}\n",
    "D"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 3,集合推导式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 2, 3}"
      ]
     },
     "execution_count": 121,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "{abs(x) for x in [-1,-2,1,2,3]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{2, 4}"
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 求两个集合的交集\n",
    "a = {1,2,5,4}\n",
    "b = {2,4,6,8}\n",
    "\n",
    "a.intersection(b)\n",
    "\n",
    "{x for x in a if x in b}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十八，类和对象"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1，面向对象基本概念\n",
    "\n",
    "* 什么是面向对象编程？\n",
    "\n",
    "POP: Process Oriented Programming. 程序被看成一系列命令的依次执行。基本封装形式为函数。 \n",
    "设计函数的基本要点是 IPO：输入Input ——> 处理Process ——> 输出Output.\n",
    "\n",
    "OOP: Object Oriented Programming. 程序被看成一系列对象的相互作用。基本的封装形式是类。\n",
    "设计类的基本要点是 RPM: 关系 Relation， 属性Property，方法 Method.\n",
    "类和类之间常用的方法包括：is（继承关系）, has（包含关系）, use（使用关系）\n",
    "\n",
    "\n",
    "* 面向对象基本术语？\n",
    "\n",
    "类： class, 抽象数据结构，数据和算法的封装。如：定义一个类：dog。\n",
    "\n",
    "对象： object, 类的实例。如：dog类的一个实例：点点dot。\n",
    "\n",
    "属性：properties，和对象关联的数据部分。如：weight 体重，breed 品种。\n",
    "\n",
    "方法：methods，和对象关联的算法部分。如：run(), eat(), bark()。\n",
    "\n",
    "\n",
    "* 面向对象编程的优点？\n",
    "\n",
    "容易使用： 封装，奇妙的句点符号。\n",
    "\n",
    "容易扩展： 继承，多态。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 2,创建类和对象\n",
    "\n",
    "class Dog(object):\n",
    "    \n",
    "    def __init__(self,name,weight,breed,age):\n",
    "        \n",
    "        self.name = name\n",
    "        self.weight = weight\n",
    "        self.breed = breed\n",
    "        \n",
    "        # __age为私有属性\n",
    "        self.__age = age\n",
    "    \n",
    "    def run(self):\n",
    "        print('%s is running...'%(self.name))\n",
    "        \n",
    "    def bark(self):\n",
    "        print('Bowwow,Bowwow,Bowwow...')\n",
    "        \n",
    "    def eat(self,food):\n",
    "        print('%s is eating %s...'%(self.name,food))\n",
    "        \n",
    "    def sleep(self):\n",
    "        print('Zzz...Zzz...Zzz...')\n",
    "    \n",
    "    # __think为私有方法\n",
    "    def __think(self):\n",
    "        print('I feel myself a hero and very handsome !')\n",
    "        \n",
    "    # speak公有方法可以调用私有方法\n",
    "    def speak(self,words = ''):\n",
    "        self.__think()\n",
    "        if(words):print(words)\n",
    "            \n",
    "    \n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 124,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "snoopy is running...\n",
      "Bowwow,Bowwow,Bowwow...\n",
      "snoopy is eating meat...\n",
      "Zzz...Zzz...Zzz...\n",
      "I feel myself a hero and very handsome !\n",
      "HaHaHa!!!\n"
     ]
    }
   ],
   "source": [
    "# 实例化一个对象\n",
    "\n",
    "snoopy = Dog('snoopy',3,'Husky',4)\n",
    "\n",
    "#调用公有属性和公有方法\n",
    "snoopy.breed\n",
    "\n",
    "\n",
    "snoopy.run()\n",
    "snoopy.bark()\n",
    "snoopy.eat('meat')\n",
    "snoopy.sleep()\n",
    "snoopy.speak('HaHaHa!!!')\n",
    "\n",
    "#私有属性和私有方法不能够直接在类外部访问。\n",
    "# snoopy.__age\n",
    "# snoopy.__think()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "### 3,获取对象信息\n",
    "\n",
    "#python中万物皆对象\n",
    "\n",
    "# type查看对象类别\n",
    "\n",
    "type(1),type(False),type(snoopy),type(len),type([1,2,3])\n",
    "\n",
    "# isinstance 测试某个对象是否属于某个类\n",
    "isinstance({1,2,3},set)\n",
    "isinstance(max,object)\n",
    "\n",
    "# object是the most base type\n",
    "print(isinstance(123,(list,str,float,int)))\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 十九，封装和继承"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 1,封装\n",
    "\n",
    "奇妙的句点符号：通过奇妙的句点符号可以召唤对象的属性和方法。\n",
    "私有属性和私有方法除外。\n",
    "\n",
    "公有属性和公有方法\n",
    "\n",
    "私有属性和私有方法：以双下划线开头\n",
    "\n",
    "定制属性和定制方法：以双下划线开头和双下划线结尾\n",
    "\n",
    "__init__ 构造函数,通过类名调用\n",
    "__str__  通过str函数调用\n",
    "__len__ 通过len函数调用\n",
    "……\n",
    "\n",
    "类属性和类方法：在__init__外部定义的为类属性,\n",
    "第一个参数不是self参数的方法为类方法。\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 126,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Animal(object):\n",
    "    \n",
    "    #类属性\n",
    "    home = 'earth'\n",
    "    \n",
    "    #类方法\n",
    "    def dream():\n",
    "        print('No deal, no hurt!')\n",
    "        \n",
    "    #定制方法\n",
    "    def __str__(self):\n",
    "        return('An animal named %s'%self.name)\n",
    "        \n",
    "    def __init__(self,name,weight,breed,age):\n",
    "        \n",
    "        self.name = name\n",
    "        self.weight = weight\n",
    "        self.breed = breed\n",
    "        \n",
    "        # __age为私有属性\n",
    "        self.__age = age\n",
    "    \n",
    "    def run(self):\n",
    "        print('%s is running...'%(self.name))\n",
    "        \n",
    "        \n",
    "    def eat(self,food):\n",
    "        print('%s is eating %s...'%(self.name,food))\n",
    "        \n",
    "    def sleep(self):\n",
    "        print('Zzz...Zzz...Zzz...')\n",
    "    \n",
    "    # __think为私有方法\n",
    "    def __think(self):\n",
    "        print('I feel myself a hero and very handsome !')\n",
    "        \n",
    "    # speak公有方法可以调用私有方法\n",
    "    def speak(self,words = ''):\n",
    "        self.__think()\n",
    "        if(words):print(words)\n",
    "    \n",
    "        \n",
    "    \n",
    "        \n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'earth'"
      ]
     },
     "execution_count": 127,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#类属性\n",
    "snoopy = Animal('snoopy',3,'Husky',4)\n",
    "snoopy.home\n",
    "Animal.home"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 通过对象能够访问，但不能够修改类属性\n",
    "#snoopy.home = 'moon'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "No deal, no hurt!\n"
     ]
    }
   ],
   "source": [
    "# 类方法只能通过类名访问，不能通过对象访问\n",
    "Animal.dream()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 130,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "snoopy is running...\n"
     ]
    }
   ],
   "source": [
    "# 通过类名也可以访问对象方法\n",
    "Animal.run(snoopy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "snoopy is running...\n"
     ]
    }
   ],
   "source": [
    "snoopy.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 132,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'An animal named snoopy'"
      ]
     },
     "execution_count": 132,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 定制方法有特殊的功能\n",
    "str(snoopy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'abc123def'"
      ]
     },
     "execution_count": 133,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 奇妙的句点符号\n",
    "\n",
    "s = 'abc#123@def'\n",
    "\n",
    "#面向过程必须记住非常多函数名，replace,upper,find\n",
    "\n",
    "#面向对象只需要输入奇妙的句点符号后按下tab键\n",
    "s.replace('#','').replace('@','')\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 134,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "execution_count": 134,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "execution_count": 135,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.__len__()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 136,
   "metadata": {},
   "outputs": [],
   "source": [
    "dir(s) # 查看全部可用属性和方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 2，继承\n",
    "\n",
    "#子类可以通过继承获得父类的属性和方法\n",
    "\n",
    "class Cat(Animal):\n",
    "    \n",
    "    def call(self):\n",
    "        print('MiaoMiaoMiao...')\n",
    "   \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 138,
   "metadata": {},
   "outputs": [],
   "source": [
    "kitty = Cat('kitty',1,'Bose',5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MiaoMiaoMiao...\n"
     ]
    }
   ],
   "source": [
    "kitty.call()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I feel myself a hero and very handsome !\n",
      "miaow...miaow...miaow...\n"
     ]
    }
   ],
   "source": [
    "kitty.speak('miaow...miaow...miaow...')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 二十，模块和包"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "一个.py文件就是一个模块。\n",
    "一个包含有__init__.py文件的文件夹就是一个包。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1，模块示范"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 142,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing mymodule.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile mymodule.py\n",
    "#!/usr/bin/env python3\n",
    "#-*- coding:utf-8 -*-\n",
    "\n",
    "'a test module'  #模块注释\n",
    "\n",
    "__author__ = 'Python_Ai_Road' #作者信息\n",
    "__version__ = 'v1.0' #版本信息\n",
    "\n",
    "def _Email():   #模块私有函数\n",
    "    print('lyhue1991@163.com')\n",
    "    \n",
    "\n",
    "def __WeChat_Official_Account():  #模块私有函数\n",
    "    print('Python与算法之美')\n",
    "    \n",
    "    \n",
    "def hello(person = 'world'): #公有函数\n",
    "    print('hello',person)\n",
    "    \n",
    "\n",
    "def test(): #测试代码\n",
    "    hello()\n",
    "    hello('China')\n",
    "    print('Contact to me:',end = '\\t')\n",
    "    _Email()\n",
    "    print('Learn more with me:', end = '\\t')\n",
    "    __WeChat_Official_Account()\n",
    "    \n",
    "\n",
    "#当直接运行该模块时，执行测试代码，而引入模块时不执行测试代码。\n",
    "if __name__ == '__main__':\n",
    "    test()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "metadata": {},
   "outputs": [],
   "source": [
    "import mymodule\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 144,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on module mymodule:\n",
      "\n",
      "NAME\n",
      "    mymodule - a test module\n",
      "\n",
      "FUNCTIONS\n",
      "    hello(person='world')\n",
      "    \n",
      "    test()\n",
      "\n",
      "VERSION\n",
      "    v1.0\n",
      "\n",
      "AUTHOR\n",
      "    Python_Ai_Road\n",
      "\n",
      "FILE\n",
      "    /home/jquser/mymodule.py\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(mymodule)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Python_Ai_Road'"
      ]
     },
     "execution_count": 145,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mymodule.__author__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 146,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'a test module'"
      ]
     },
     "execution_count": 146,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mymodule.__doc__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello world\r\n",
      "hello China\r\n",
      "Contact to me:\tlyhue1991@163.com\r\n",
      "Learn more with me:\tPython与算法之美\r\n"
     ]
    }
   ],
   "source": [
    "!python mymodule.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2，包示范"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "metadata": {},
   "outputs": [],
   "source": [
    "!mkdir Animal"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing Animal/__init__.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile Animal/__init__.py\n",
    "#!/usr/bin/env python3\n",
    "#-*- coding:utf-8 -*-\n",
    "\n",
    "'Animal module for fun!'  #模块注释\n",
    "__author__ = 'Python_Ai_Road' #作者信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 150,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing Animal/Animal.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile Animal/Animal.py\n",
    "class Animal(object):\n",
    "    def __init__(self,name):\n",
    "        self.name = name\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing Animal/Dog.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile Animal/Dog.py\n",
    "from Animal.Animal import Animal\n",
    "class Dog(Animal):\n",
    "    def call(self):\n",
    "        print('bowwow...bowwow...bowwow...')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing Animal/Cat.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile Animal/Cat.py\n",
    "from Animal.Animal import Animal\n",
    "class Cat(Animal):\n",
    "    def call(self):\n",
    "        print('miaow...miaow...miaow...')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on package Animal:\n",
      "\n",
      "NAME\n",
      "    Animal - Animal module for fun!\n",
      "\n",
      "PACKAGE CONTENTS\n",
      "    Animal\n",
      "    Cat\n",
      "    Dog\n",
      "\n",
      "AUTHOR\n",
      "    Python_Ai_Road\n",
      "\n",
      "FILE\n",
      "    /home/jquser/Animal/__init__.py\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import Animal\n",
    "help(Animal)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 154,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "bowwow...bowwow...bowwow...\n"
     ]
    }
   ],
   "source": [
    "from Animal.Dog import Dog\n",
    "snoopy = Dog('snoopy')\n",
    "snoopy.call()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "miaow...miaow...miaow...\n"
     ]
    }
   ],
   "source": [
    "from Animal.Cat import Cat\n",
    "kitty = Cat('kitty')\n",
    "kitty.call()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(完)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](Python与算法之美.png)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
